#include "stdafx.h"
#include "ffmpeg.h"
#include "com_core_def.h"

HRESULT process_ffmpeg_raw_data_to_IMFSample(IMFSample** ppNewSample,PBYTE pRawData,UINT nDataSize,AVPacket* packet,AVRational time_base,LONGLONG start_time,LONGLONG duration)
{
	if (packet == NULL)
		return E_POINTER;
	HRESULT hr = S_OK;
	CComPtr<IMFSample> pSample = NULL;
	CComPtr<IMFMediaBuffer> pBuffer = NULL;
	hr = MFCreateSample(&pSample);
	if (FAILED(hr))
		return hr;
	DWORD dwDataLen = nDataSize;
	hr = MFCreateMemoryBuffer(dwDataLen,&pBuffer);
	if (FAILED(hr))
		return hr;
	PBYTE pData = NULL;
	hr = pBuffer->Lock(&pData,NULL,NULL);
	if (pData == NULL)
		return hr;
	RtlCopyMemory(pData,pRawData,dwDataLen);
	pBuffer->Unlock();
	pBuffer->SetCurrentLength(dwDataLen);
	hr = pSample->AddBuffer(pBuffer);
	LONGLONG pts = packet->pts;
	if (pts == AV_NOPTS_VALUE)
		pts = packet->dts;
	if (start_time != 0 && pts != AV_NOPTS_VALUE)
		pts -= av_rescale(start_time,time_base.den,AV_TIME_BASE * time_base.num);
	pSample->SetSampleTime(pts != AV_NOPTS_VALUE ? (av_q2d(time_base) * pts * MF_REF_TIME_BASE):0);
	if (duration > 0)
		pSample->SetSampleDuration(duration);
	*ppNewSample = pSample;
	(*ppNewSample)->AddRef();
	return hr;
}